package com.itheima.reggie.common;

import com.itheima.reggie.entity.LoggingEvent;
import com.itheima.reggie.service.LoggingEventService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author : xyiaao
 * @createDate : 2022/2/22 20:08
 */
@Aspect
@Component
public class LogAdvice {

    @Autowired
    private LoggingEventService loggingEventService;

    @Pointcut("execution(* com.itheima.reggie.controller.*Controller.*(..))")
    private void controllerPt() {

    }

    @Around("LogAdvice.controllerPt()")
    public Object controllerLog(ProceedingJoinPoint pjp) throws Throwable {

        LoggingEvent loggingEvent = BaseContext.getLoggingEvent();
        try {
            // 获取执行的签名对象
            Signature signature = pjp.getSignature();
            // 获取类名并设置
            loggingEvent.setClassName(signature.getDeclaringType().getSimpleName());
            // 获取方法名并设置
            loggingEvent.setMethodName(signature.getName());
            // 获取参数并设置
            loggingEvent.setParams(Arrays.toString(pjp.getArgs()));
            loggingEvent.setCreateTime(LocalDateTime.now());
            return pjp.proceed();
        } catch (Throwable e) {
            loggingEvent.setIsError(1);
            loggingEvent.setInfo(e.getMessage());
            throw e;
        } finally {
            loggingEventService.save(loggingEvent);
        }
    }
}
